package com.cracker.websocket.server.service.impl;

import com.cracker.websocket.server.constant.CmdConstant;
import com.cracker.websocket.server.dto.CmdDto;
import com.cracker.websocket.server.dto.message.ChatRoomMessageDto;
import com.cracker.websocket.server.service.ChatRoomService;
import com.cracker.websocket.server.service.MessageHandler;
import com.cracker.websocket.server.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;

/**
 * 聊天室
 */
@Component
@Slf4j
public class MessageHandlerImplChatRoom implements MessageHandler {
    @Autowired
    private ChatRoomService chatRoomService;
    @Autowired
    private MessageService messageService;

    @Override
    public void doCmd(Session session, CmdDto cmdDto) throws IOException {
        switch (cmdDto.getCmd()) {
            case CmdConstant.CHATROOM_JOIN: // 加入聊天室
                chatRoomService.join(session, cmdDto.getTargetId());
                break;
            case CmdConstant.CHATROOM_MSG: // 发送消息
                ChatRoomMessageDto messageDto = messageService.decode(cmdDto.getData(), ChatRoomMessageDto.class);
                messageDto.setSendUserId(cmdDto.getUserEntity().getId());
                chatRoomService.broadcast(session, cmdDto.getTargetId(), messageDto);
                break;
        }
    }
}
